using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using SkinnedModelPipeline;
using SkinnedModel;


namespace animations
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Model tipito;
        Vector3 modelPos = Vector3.Zero;

        List<Actor> actores = new List<Actor>();

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            Actor primerActor = new Actor();
            primerActor.mod = Content.Load<Model>("dude");

            primerActor.skinningData = primerActor.mod.Tag as SkinningData;

            if (primerActor.skinningData == null)
            
                throw new InvalidOperationException("This model not contain a SkinningData tag");
            primerActor.animationPlayer = new AnimationPlayer(primerActor.skinningData);

            AnimationClip clip = primerActor.skinningData.AnimationClips["Take 001"];

            primerActor.animationPlayer.StartClip(clip);

            primerActor.position = new Vector3(-100, 0, 0);
            actores.Add(primerActor);

            Actor segundoActor = new Actor();
            segundoActor.mod = Content.Load<Model>("dude");

            segundoActor.skinningData = segundoActor.mod.Tag as SkinningData;

            if (segundoActor.skinningData == null)

                throw new InvalidOperationException("This model not contain a SkinningData tag");
            segundoActor.animationPlayer = new AnimationPlayer(segundoActor.skinningData);

            AnimationClip clip2 = segundoActor.skinningData.AnimationClips["Take 001"];

            segundoActor.animationPlayer.StartClip(clip2);

            segundoActor.position = new Vector3(100, 0, 0);

            actores.Add(segundoActor);
            // TODO: use this.Content to load your game content here
        }
        
        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            //cameraRotation++;
            // TODO: Add your update logic here
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                actores[0].position.Z--;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                actores[0].position.Z++;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                actores[0].position.X--;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                actores[0].position.X++;
            }
            BoundingSphere bs, bs2;
            //animationPlayer.Update(gameTime.ElapsedGameTime, true, Matrix.Identity);
            for(int i = 0; i < actores.Count;i++)
            {
                Actor actor = actores[i];
                actor.animationPlayer.Update(gameTime.ElapsedGameTime, true, Matrix.Identity);
                foreach (ModelMesh mesh in actor.mod.Meshes)
                {
                    bs = mesh.BoundingSphere;
                    bs.Center = Vector3.Transform(bs.Center, Matrix.CreateTranslation(actor.position)); //sigue al origne del objeto (el centro) (modelpos iria en actor)

                    for (int j = i + 1; j < actores.Count; j++)
                    {
                        Actor actor2 = actores[j];
                        //bs2.Center = Vector3.Transform(bs.Center, Matrix.CreateTranslation(actor2.position)); //sigue al origne del objeto (el centro) (modelpos iria en actor)
                        foreach (ModelMesh meshin in actor2.mod.Meshes)
                        {
                            bs2 = meshin.BoundingSphere;
                            bs2.Center = Vector3.Transform(bs2.Center, Matrix.CreateTranslation(actor2.position));
                                if(bs.Intersects(bs2))
                                {
                                    actor.hit(actor2);
                                    actor2.hit(actor);
                                }
                        }
                    }
                }
            }
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 
        float cameraArc = 0;
        float cameraDistance = 120;
        float cameraRotation = 0;
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            foreach (Actor actor in actores)
            {
                // TODO: Add your drawing code here
                Matrix[] bones = actor.animationPlayer.GetSkinTransforms();

                float aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width / (float)graphics.GraphicsDevice.Viewport.Height;

                Matrix view =
                Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) *
                Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
                Matrix.CreateTranslation(actor.position) *
                Matrix.CreateLookAt(new Vector3(0, 0, -cameraDistance), new Vector3(0, 0, 0), Vector3.Up);
                Matrix proyection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1, 10000);

                foreach (ModelMesh mesh in actor.mod.Meshes)
                {
                    foreach (Effect effect in mesh.Effects)
                    {
                        effect.Parameters["Bones"].SetValue(bones);
                        effect.Parameters["View"].SetValue(view);
                        effect.Parameters["Projection"].SetValue(proyection);
                    }
                    mesh.Draw();
                }
            }
            base.Draw(gameTime);
        }
    }
}
